package com.example.chenling

import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.chenling.database.StudentDatabase
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class MainViewModel @Inject constructor(private val database: StudentDatabase) : ViewModel() {

    private val _studentList = MutableLiveData<List<Student>>()
    val studentList: LiveData<List<Student>> = _studentList

    init {
        loadStudents()
    }

    fun loadStudents() {
        viewModelScope.launch {
            try {
                val students = database.studentDao().getAllStudents()
                _studentList.postValue(students)
            } catch (e: Exception) {
                Log.e("MainViewModel", "Error loading students", e)
            }
        }
    }

    fun addStudent(student: Student) {
        viewModelScope.launch {
            try {
                database.studentDao().insertStudent(student)
                loadStudents()
            } catch (e: Exception) {
                Log.e("MainViewModel", "Error adding student", e)
            }
        }
    }
}